package com.shoujifeng.snowmusic.player;

import java.util.ArrayList;
import java.util.HashMap;

import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.weibo.TencentWeibo;

import com.shoujifeng.snowmusic.db.DatabaseUtil;
import com.shoujifeng.snowmusic.player.R;
import com.shoujifeng.snowmusic.player.http.GlobalValue;
import com.shoujifeng.snowmusic.player.http.ServerAccess;

/**
 * 登陆
 * @author luo
 *
 */
public class LoginActivity extends Activity{
	private Button breakBtn;
	private Button registerBtn;
	private TextView unknowTxt;
	private EditText numberEdt;
	private EditText passwordEdt;
	private Button loginBtn;
	private View loginTX;
	private View loginSINA;
	
	private ServerAccess serverAccess;
	private final int UPDATE_DATA = 0;
	private final int SHARE_DATA	= 1;
	private String number;
	private String password;
	private Thread accThread;
	private String code;
	private HashMap<String, Object> map ;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		initGlobalValue();
		init();
		
		ShareSDK.initSDK(this);
	}
	
	@Override
	protected void onDestroy() {
		ShareSDK.stopSDK(this);
		super.onDestroy();
	}



	private void init(){
		serverAccess = new ServerAccess(LoginActivity.this);
		breakBtn = (Button) findViewById(R.id.breakBtn);
		breakBtn.setOnClickListener(onClickListener);
		registerBtn = (Button) findViewById(R.id.registerBtn);
		registerBtn.setOnClickListener(onClickListener);
		unknowTxt = (TextView) findViewById(R.id.unknowTxt);
		unknowTxt.setOnClickListener(onClickListener);
		loginTX = (View) findViewById(R.id.login_tx);
		loginSINA = (View) findViewById(R.id.login_sina);
		
		numberEdt = (EditText) findViewById(R.id.number);
		passwordEdt = (EditText) findViewById(R.id.password);
		loginBtn = (Button) findViewById(R.id.loginBtn);
		loginBtn.setOnClickListener(onClickListener);
		loginTX.setOnClickListener(onClickListener);
		loginSINA.setOnClickListener(onClickListener);
	}
	
	private View.OnClickListener onClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.breakBtn:{
				finish();
				overridePendingTransition(R.anim.no_move, R.anim.right_out);
			}
				break;
			case R.id.registerBtn:{
				Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.right_in, R.anim.left_out);
			}	
				break;
			case R.id.unknowTxt:{
				Intent intent = new Intent(LoginActivity.this,UnknowPasswordActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.right_in, R.anim.left_out);
			}
			   break;
			case R.id.loginBtn:{
					
					number = numberEdt.getText().toString();
					password = passwordEdt.getText().toString();
					if(number.equals("")){
						Toast.makeText(LoginActivity.this, "账号不能为空", Toast.LENGTH_SHORT)
						.show();
					}else
					if(password.equals("")){
						Toast.makeText(LoginActivity.this, "密码不能为空", Toast.LENGTH_SHORT)
						.show();
					}else{
						accThread = new Thread(runnable);
						accThread.start();
					}
					
			}  
			break;
			case R.id.login_tx:
			{
				shareLogin();
				Toast.makeText(LoginActivity.this, "腾讯微博登录...", Toast.LENGTH_SHORT)
				.show();
			}
				break;
			case R.id.login_sina:
			{
				shareLogin(SinaWeibo.NAME);
				Toast.makeText(LoginActivity.this, "新浪微博登录...", Toast.LENGTH_SHORT)
				.show();
			}
				break;
			default:
				break;
			}
		}
	};
	
	private void shareLogin(String name) {
		Platform weibo = ShareSDK.getPlatform(LoginActivity.this, name);
		weibo.setPlatformActionListener(new PlatformActionListener() {
			
			@Override
			public void onError(Platform arg0, int arg1, Throwable arg2) {
				// TODO Auto-generated method stub
				Toast.makeText(LoginActivity.this, "登陆失败, 请检查!", Toast.LENGTH_SHORT)
				.show();
			}
			
			@Override
			public void onComplete(Platform arg0, int arg1, HashMap<String, Object> map) {
				// TODO Auto-generated method stub
				
				ServerAccess.code     = "1";
				ServerAccess.number   = map.get("name").toString();
				ServerAccess.nickname = map.get("name").toString();
				ServerAccess.uid = Integer.parseInt(map.get(ServerAccess.ID).toString());
				
				Message message = new Message();
				message.what = SHARE_DATA;
				handler.sendMessage(message);				
			}
			
			@Override
			public void onCancel(Platform arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
		});
		weibo.showUser(null);//获取登陆用户资料
	}
	
	private void shareLogin() {
		Platform weibo = ShareSDK.getPlatform(LoginActivity.this, TencentWeibo.NAME);
		weibo.setPlatformActionListener(new PlatformActionListener() {
			
			@Override
			public void onError(Platform arg0, int arg1, Throwable arg2) {
				// TODO Auto-generated method stub
				Toast.makeText(LoginActivity.this, "登陆失败, 请检查!", Toast.LENGTH_SHORT)
				.show();
			}
			
			@Override
			public void onComplete(Platform arg0, int arg1, HashMap<String, Object> map) {
				// TODO Auto-generated method stub
				
				ServerAccess.code     = "1";
				ServerAccess.number   = map.get("nick").toString();
				ServerAccess.nickname = map.get("nick").toString();
				
				String strIdString = map.get("openid").toString();
				if(strIdString.length() > 8) {
					String strid = strIdString.substring(strIdString.length() - 9, strIdString.length() - 1).toString();
					
					long uid = Long.valueOf(strid,16);
					ServerAccess.uid = uid;
				}else {
					ServerAccess.uid = Long.parseLong(map.get(ServerAccess.ID).toString());
				}
				
				
				Message message = new Message();
				message.what = SHARE_DATA;
				handler.sendMessage(message);				
			}
			
			@Override
			public void onCancel(Platform arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
		});
		weibo.showUser(null);//获取登陆用户资料
	}
	
	
	private void initGlobalValue() {
		GlobalValue.initSDAddr();
		GlobalValue.addUrl(ServerAccess.LOGIN,
				"http://www.snowmusic.com.cn/mobile_api/login.php");
	}
	

	protected Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case UPDATE_DATA: {
				if(code.equals("0")){
					Toast.makeText(LoginActivity.this, "账号或密码错误", Toast.LENGTH_SHORT)
					.show();
				}
				if(code.equals("1")){
					ServerAccess.code     = "1";
					ServerAccess.number   = number;
					ServerAccess.nickname = map.get(ServerAccess.NICKNAME).toString();
					ServerAccess.uid = Integer.parseInt(map.get(ServerAccess.USER_ID).toString());
					Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT)
					.show();
					writeUserToFile();  //登陆的信息写入到配置文件
					writeConllect(ServerAccess.uid);
					
					finish();
					overridePendingTransition(R.anim.no_move, R.anim.right_out);
				}
			}
				break;
			case SHARE_DATA:
			{
				Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
				
				writeUserToSelf();  //登陆的信息写入到配置文件
				writeConllect(ServerAccess.uid);
				
				finish();
				overridePendingTransition(R.anim.no_move, R.anim.right_out);
			}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
		{
			finish();
			
			overridePendingTransition(R.anim.no_move, R.anim.right_out);
		}
			break;

		default:
			break;
		}
		
		return super.onKeyDown(keyCode, event);
	}

	// 创建多线程获取数据
	protected Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				map =  new HashMap<String, Object>();
				map = serverAccess.login(number,password );
				code = map.get(ServerAccess.CODE).toString();
				sendMessage(UPDATE_DATA);

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	};

	// 发送消息到Handler
	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}
	
	private void writeUserToFile(){
		
		try {
			//写入数据到配置文件中        关闭状态
		    SharedPreferences spf = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
		      Editor edit = spf.edit();
		      edit.putString(ServerAccess.CODE, "1");
		      edit.putString(ServerAccess.NUMBER, number);
		      edit.putString(ServerAccess.NICKNAME, map.get(ServerAccess.NICKNAME).toString());
		      edit.putString(ServerAccess.UID, map.get(ServerAccess.USER_ID).toString());
		      edit.commit();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	private void writeUserToSelf(){
		//写入数据到配置文件中        关闭状态
	    SharedPreferences spf = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
	      Editor edit = spf.edit();
	      edit.putString(ServerAccess.CODE, ServerAccess.code);
	      edit.putString(ServerAccess.NUMBER, ServerAccess.number);
	      edit.putString(ServerAccess.NICKNAME, ServerAccess.nickname);
	      edit.putString(ServerAccess.UID, ServerAccess.uid+"");
	      edit.commit();
	}
	
	//获取收藏数据
	//By Kress
	private void writeConllect(final long uid)
	{
		new AsyncTask<Integer, Integer, Integer>()
		{

			@Override
			protected Integer doInBackground(Integer... params) {
				try {
					ArrayList<HashMap<String, Object>> arrayList = serverAccess.getConllect(uid, -1, new String[]{"index"});
					if(arrayList != null && arrayList.size() > 0) 
					{
						DatabaseUtil db = new DatabaseUtil(LoginActivity.this);
						db.clearConllect();
						
						int count = arrayList.size();
						for(int i = 0; i < count; i++) {
							HashMap<String, Object> map = arrayList.get(i);
							
							db.insertConllect(Integer.parseInt(map.get("index").toString()), uid);
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				return null;
			}
			
		}.execute(0);
	}
}
